package com.zhou.spring.cloud.balancer.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.cache.LoadBalancerCacheManager;
import org.springframework.cloud.loadbalancer.config.LoadBalancerZoneConfig;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * loadbalancer的client 只能配置如下三种处理类
 * 另外需要注意设置系统的默认zone
 */
public class MyLoadBalancerClientsConfiguration {

    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory
                .getLazyProvider(name, ServiceInstanceListSupplier.class),
                name);
    }


    //设置可以根据请求的hearer获取到适合的zone
    @Bean
    public ServiceInstanceListSupplier myZonePreferenceServiceInstanceListSupplier(ConfigurableApplicationContext context) {
        LoadBalancerZoneConfig zoneConfig = context.getBean(LoadBalancerZoneConfig.class);
        ServiceInstanceListSupplier baseSupplier = ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient()
                .build(context);
        MyZonePreferenceServiceInstanceListSupplier myZonePreferenceServiceInstanceListSupplier = new MyZonePreferenceServiceInstanceListSupplier(baseSupplier, zoneConfig);
        ObjectProvider<LoadBalancerCacheManager> cacheManagerProvider = context
                .getBeanProvider(LoadBalancerCacheManager.class);
        if (cacheManagerProvider.getIfAvailable() != null) {
            return new CachingServiceInstanceListSupplier(myZonePreferenceServiceInstanceListSupplier, cacheManagerProvider.getIfAvailable());
        }
        return myZonePreferenceServiceInstanceListSupplier;
    }

    //@Bean
    public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
            ConfigurableApplicationContext context) {
        return ServiceInstanceListSupplier.builder()
                .withDiscoveryClient()
                .withZonePreference()
                .withCaching()
                .build(context);
    }

    @Bean
    public MyBalancerLifecycle myBalancerLifecycle() {
        return new MyBalancerLifecycle();
    }


}
